/*
 * @Author: 13177709051 3506463075@qq.com
 * @Date: 2024-11-08 14:27:51
 * @LastEditors: 13177709051 3506463075@qq.com
 * @LastEditTime: 2024-11-08 14:32:45
 * @FilePath: /test/mysql-API.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <mysql/mysql.h>
#define HOST "127.0.0.1"
#define USER "root"
#define PASSWD ""
#define DBNAME "test_db"
void add(MYSQL *mysql)
{
    char *sql = "insert into test_tb values(null, 18, '张三', 88.88), (null, 17, '李四',77);";
    int ret = mysql_query(mysql, sql);
    if (ret != 0)
    {
        printf("mysql query error:%s\n", mysql_error(mysql));
        return;
    }
    return;
}
void mod(MYSQL *mysql)
{
    char *sql = "update test_tb set age=34 where name='张三';";
    int ret = mysql_query(mysql, sql);
    if (ret != 0)
    {
        printf("mysql query error:%s\n", mysql_error(mysql));
        return;
    }
    return;
}
void del(MYSQL *mysql)
{
    char *sql = "delete from test_tb where name='张三';";
    int ret = mysql_query(mysql, sql);
    if (ret != 0)
    {
        printf("mysql query error:%s\n", mysql_error(mysql));
        return;
    }
    return;
}
void get(MYSQL *mysql)
{
    char *sql = "select * from test_tb;";
    int ret = mysql_query(mysql, sql);
    if (ret != 0)
    {
        printf("mysql query error:%s\n", mysql_error(mysql));
        return;
    }
    MYSQL_RES *res = mysql_store_result(mysql);
    if (res == NULL)
    {
        printf("mysql store result error:%s\n", mysql_error(mysql));
        return;
    }
    int row = mysql_num_rows(res);
    int col = mysql_num_fields(res);
    printf("%10s%10s%10s%10s\n", "ID", "年龄", "姓名", "成绩");
    for (int i = 0; i < row; i++)
    {
        MYSQL_ROW row_data = mysql_fetch_row(res);
        for (int i = 0; i < col; i++)
        {
            printf("%10s", row_data[i]);
        }
        printf("\n");
    }
    mysql_free_result(res);
    return;
}
int main()
{
    MYSQL *mysql = mysql_init(NULL);
    if (mysql == NULL)
    {
        printf("init mysql handle failed!\n");
        return -1;
    }
    if (mysql_real_connect(mysql, HOST, USER, PASSWD, DBNAME, 0, NULL, 0) == NULL)
    {
        printf("mysql connect error:%s\n", mysql_error(mysql));
        return -1;
    }
    mysql_set_character_set(mysql, "utf8");
    // mysql_select_db(mysql, DBNAME);
    add(mysql);
    get(mysql);
    mod(mysql);
    get(mysql);
    del(mysql);
    get(mysql);
    mysql_close(mysql);
    return 0;
}
